<template>
  <view class="drive-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 地图容器 -->
    <map
      id="map"
      class="map"
      :latitude="latitude"
      :longitude="longitude"
      :markers="markers"
      :polyline="polyline"
      :scale="scale"
      show-location
      @regionchange="onMapRegionChange"
      @markertap="onMarkerTap"
    ></map>

    <!-- 路线信息卡片 -->
    <view class="route-card" v-if="routeInfo">
      <view class="route-header">
        <view class="route-title">
          <text class="distance">{{ routeInfo.distance }}</text>
          <text class="duration">{{ routeInfo.duration }}</text>
        </view>
        <button class="navigate-btn" @tap="startNavigation">开始导航</button>
      </view>
      <view class="route-steps">
        <view 
          class="step-item"
          v-for="(step, index) in routeInfo.steps"
          :key="index"
        >
          <text class="step-instruction">{{ step.instruction }}</text>
          <text class="step-distance">{{ step.distance }}</text>
        </view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-box">
      <view class="search-input">
        <view class="start-point">
          <text class="iconfont icon-location"></text>
          <text class="location-text">{{ currentLocation }}</text>
        </view>
        <view class="end-point">
          <text class="iconfont icon-search"></text>
          <input 
            class="search-input-field" 
            v-model="searchKeyword"
            placeholder="请输入目的地"
            @input="onSearchInput"
            @confirm="onSearchConfirm"
          />
        </view>
      </view>
      
      <!-- 搜索结果列表 -->
      <view class="search-results" v-if="searchResults.length > 0">
        <view 
          class="result-item"
          v-for="(item, index) in searchResults"
          :key="index"
          @tap="selectDestination(item)"
        >
          <view class="result-name">{{ item.title }}</view>
          <view class="result-address">{{ item.address }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
  data() {
    return {
      latitude: 39.908823,
      longitude: 116.397470,
      scale: 16,
      markers: [],
      polyline: [],
      currentLocation: '正在获取位置...',
      routeInfo: null,
      map: null,
      searchKeyword: '',
      searchResults: [],
      searchTimer: null,
      isIOS: false
    }
  },

  onLoad() {
    // iOS 首次进入自动刷新
    // this.isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
    // if (this.isIOS && !sessionStorage.getItem('iosRefreshed_drive')) {
    //   sessionStorage.setItem('iosRefreshed_drive', 'true');
    //   window.location.reload();
    //   return;
    // }
    this.initMap()
    this.getCurrentLocation()
    
    // 获取页面参数
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = currentPage.$page?.options
    
    if (options?.address) {
      // 如果有地址参数，自动填入搜索框并搜索
      this.searchKeyword = decodeURIComponent(options.address)
      this.onSearchConfirm()
    }
  },
  onShow() {
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },

    // 初始化地图
    initMap() {
      this.map = uni.createMapContext('map', this)
    },

    // 获取当前位置
    async getCurrentLocation() {
      try {
        // 获取当前页面URL
        const currentUrl = window.location.href.split('#')[0]
        
        // 获取jssdk配置
        const configRes = await uni.request({
          url: `${uni.$config.baseUrl}/wx/jssdk/config`,
          method: 'GET',
          data: {
            url: currentUrl
          }
        })
        
        if (configRes.statusCode === 200 && configRes.data.code === 200) {
          const config = configRes.data.data
          
          // 加载jweixin-module
          const jWeixin = require('jweixin-module')
          
          // 配置微信JSSDK
          jWeixin.config({
            debug: false,
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: ['getLocation', 'openLocation']
          })
          
          // 使用微信JSSDK获取位置
          jWeixin.ready(() => {
            jWeixin.getLocation({
              type: 'gcj02',
              success: (res) => {
                console.log('微信定位成功:', res)
                
                // 更新地图位置信息
                this.latitude = res.latitude
                this.longitude = res.longitude
                
                // 获取位置名称
                this.getLocationName(res.latitude, res.longitude)
              },
              fail: () => {
                console.error('微信定位失败')
                // 如果微信定位失败，尝试使用IP定位
                this.getLocationByIP()
              }
            })
          })
          
          jWeixin.error((err) => {
            console.error('微信JSSDK配置失败:', err)
            // 如果微信JSSDK配置失败，尝试使用IP定位
            this.getLocationByIP()
          })
        } else {
          console.error('获取JSSDK配置失败')
          // 如果获取配置失败，尝试使用IP定位
          this.getLocationByIP()
        }
      } catch (error) {
        console.error('加载jweixin-module失败:', error)
        // 如果加载jweixin-module失败，尝试使用IP定位
        this.getLocationByIP()
      }
    },
    
    // 使用IP定位
    getLocationByIP() {
      // 使用腾讯地图IP定位API获取位置
      uni.request({
        url: `${uni.$config.baseUrl}/map/location/v1/ip`,
        data: {
          key: 'GJZBZ-5ZV6G-ID2QK-Q6ODP-WNIPQ-HZFB4'
        },
        success: (res) => {
          if (res.data.code === 200) {
            const location = res.data.data.location;
            this.latitude = location.lat;
            this.longitude = location.lng;
            
            // 获取位置名称
            this.getLocationName(location.lat, location.lng);
          } else {
            console.error('IP定位失败:', res.data);
            // 定位失败，使用默认位置（北京）
            this.useDefaultLocation();
          }
        },
        fail: (err) => {
          console.error('请求IP定位失败:', err);
          // 请求失败，使用默认位置（北京）
          this.useDefaultLocation();
        }
      });
    },
    
    // 使用默认位置（北京）
    useDefaultLocation() {
      this.latitude = 39.908692;
      this.longitude = 116.397470;
      
      // 获取位置名称
      this.getLocationName(this.latitude, this.longitude);
    },

    // 获取位置名称
    getLocationName(latitude, longitude) {
      // 调用后端API获取位置名称
      uni.request({
        url: `${uni.$config.baseUrl}/map/geocoder/v1/reverse`,
        data: {
          location: `${latitude},${longitude}`,
          key: 'GJZBZ-5ZV6G-ID2QK-Q6ODP-WNIPQ-HZFB4'
        },
        success: (res) => {
          if (res.data.code === 200 ) {
            this.currentLocation = res.data.data.address
          }
        }
      })
    },

    // 搜索输入处理
    onSearchInput(e) {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      
      // 设置新的定时器，300ms后执行搜索
      this.searchTimer = setTimeout(() => {
        if (this.searchKeyword.trim()) {
          this.searchPlaces(this.searchKeyword.trim())
        } else {
          this.searchResults = []
        }
      }, 300)
    },

    // 搜索确认处理
    onSearchConfirm() {
      if (this.searchKeyword.trim()) {
        this.searchPlaces(this.searchKeyword.trim())
      }
    },

    // 选择目的地
    selectDestination(place) {
      this.searchKeyword = place.title
      this.searchResults = []
      
      // 更新终点标记
      const endPoint = {
        latitude: place.location.lat,
        longitude: place.location.lng,
        name: place.title,
        address: place.address
      }
      
      this.planRoute(endPoint)
    },

    // 开始导航
    startNavigation() {
      if (!this.routeInfo) return
      
      // 调用腾讯地图APP进行导航
      uni.openLocation({
        latitude: this.markers[this.markers.length - 1].latitude,
        longitude: this.markers[this.markers.length - 1].longitude,
        name: this.routeInfo.endPoint,
        address: this.routeInfo.endAddress,
        scale: 18
      })
    },

    // 地图区域变化事件
    onMapRegionChange(e) {
      // 可以在这里处理地图视野变化
    },

    // 标记点击事件
    onMarkerTap(e) {
      const marker = this.markers.find(m => m.id === e.markerId)
      if (marker) {
        // 显示标记点信息
        uni.showToast({
          title: marker.title,
          icon: 'none'
        })
      }
    },

    // 规划路线
    planRoute(endPoint) {
      // 调用后端API规划路线
      uni.request({
        url: `${uni.$config.baseUrl}/map/direction/v1/driving`,
        data: {
          from: `${this.latitude},${this.longitude}`,
          to: `${endPoint.latitude},${endPoint.longitude}`,
          key: 'GJZBZ-5ZV6G-ID2QK-Q6ODP-WNIPQ-HZFB4'
        },
        success: (res) => {
          if (res.data.code === 200 ) {
            const route = res.data.data.routes[0]
            
            // 设置路线信息
            this.routeInfo = {
              distance: this.formatDistance(route.distance),
              duration: this.formatDuration(route.duration),
              endPoint: endPoint.name,
              endAddress: endPoint.address,
              steps: route.steps.map(step => ({
                instruction: step.instruction,
                distance: this.formatDistance(step.distance)
              }))
            }

            // 更新地图上的路线
            this.polyline = [{
              points: route.polyline.map(point => ({
                latitude: point.lat,
                longitude: point.lng
              })),
              color: '#2B85E4',
              width: 6
            }]

            // 更新标记点
            this.markers = [
              {
                id: 1,
                latitude: this.latitude,
                longitude: this.longitude,
                title: '当前位置',
                iconPath: '/static/start-marker.png',
                width: 30,
                height: 30
              },
              {
                id: 2,
                latitude: endPoint.latitude,
                longitude: endPoint.longitude,
                title: endPoint.name,
                iconPath: '/static/end-marker.png',
                width: 30,
                height: 30
              }
            ]

            // 调整地图视野以包含起点和终点
            this.map.includePoints({
              points: this.markers,
              padding: [80, 80, 80, 80]
            })
          }
        }
      })
    },

    // 格式化距离
    formatDistance(meters) {
      return meters > 1000 
        ? (meters / 1000).toFixed(1) + 'km'
        : Math.round(meters) + 'm'
    },

    // 格式化时间
    formatDuration(seconds) {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      
      if (hours > 0) {
        return `${hours}小时${minutes}分钟`
      }
      return `${minutes}分钟`
    },

    // 搜索地点
    searchPlaces(keyword) {
      // 构建搜索范围（以当前位置为中心，半径10公里）
      const boundary = `nearby(${this.latitude},${this.longitude},10000)`
      
      uni.request({
        url: `${uni.$config.baseUrl}/map/place/v1/search`,
        data: {
          keyword,
          boundary,
          key: 'GJZBZ-5ZV6G-ID2QK-Q6ODP-WNIPQ-HZFB4',
          page_size: 10,
          page_index: 1
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.searchResults = res.data.data
          } else {
            this.searchResults = []
            uni.showToast({
              title: '搜索失败',
              icon: 'none'
            })
          }
        },
        fail: () => {
          this.searchResults = []
          uni.showToast({
            title: '搜索失败',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.drive-container {
  height: 100vh;
  background: #F5F5F5;
  position: relative;

  .custom-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 88rpx;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    z-index: 100;
    
    .left {
      width: 88rpx;
      display: flex;
      align-items: center;
      
      .iconfont {
        font-size: 36rpx;
        color: #333333;
      }
    }
    
    .center {
      flex: 1;
      text-align: center;
      font-size: 32rpx;
      color: #333333;
      font-weight: 500;
    }
    
    .right {
      width: 88rpx;
    }
  }

  .map {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
  }

  .search-box {
    position: fixed;
    top: 108rpx;
    left: 30rpx;
    right: 30rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    z-index: 99;

    .search-input {
      padding: 20rpx;

      .start-point, .end-point {
        display: flex;
        align-items: center;
        height: 80rpx;
        padding: 0 20rpx;

        .iconfont {
          font-size: 36rpx;
          color: #2B85E4;
          margin-right: 20rpx;
        }

        .location-text {
          font-size: 28rpx;
          color: #333333;
          flex: 1;
        }

        .search-input-field {
          flex: 1;
          font-size: 28rpx;
          color: #333333;
          height: 80rpx;
        }
      }

      .start-point {
        border-bottom: 2rpx solid #F5F5F5;
      }
    }

    .search-results {
      max-height: 600rpx;
      overflow-y: auto;
      background: #FFFFFF;
      border-radius: 0 0 16rpx 16rpx;

      .result-item {
        padding: 20rpx;
        border-bottom: 2rpx solid #F5F5F5;

        .result-name {
          font-size: 28rpx;
          color: #333333;
          margin-bottom: 8rpx;
        }

        .result-address {
          font-size: 24rpx;
          color: #999999;
        }

        &:active {
          background: #F5F5F5;
        }
      }
    }
  }

  .route-card {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #FFFFFF;
    border-radius: 32rpx 32rpx 0 0;
    padding: 30rpx;
    z-index: 99;

    .route-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;

      .route-title {
        .distance {
          font-size: 36rpx;
          color: #333333;
          font-weight: 500;
          margin-right: 20rpx;
        }

        .duration {
          font-size: 28rpx;
          color: #666666;
        }
      }

      .navigate-btn {
        background: #2B85E4;
        color: #FFFFFF;
        font-size: 28rpx;
        padding: 16rpx 40rpx;
        border-radius: 32rpx;
        border: none;
      }
    }

    .route-steps {
      max-height: 400rpx;
      overflow-y: auto;

      .step-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 2rpx solid #F5F5F5;

        .step-instruction {
          flex: 1;
          font-size: 28rpx;
          color: #333333;
          margin-right: 20rpx;
        }

        .step-distance {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }
  }
}
</style> 